﻿namespace Sai.Cecil
{
	using Sai.Core.Introspection;
	using Mono.Cecil;

	/// <summary>
	/// Factory type extension to build a declarations from equivalent mono definition objects.
	/// </summary>
	public static class FieldDefinitionExtensions
	{
		/// <summary>
		/// Extension method to create a field declaration from a field definition.
		/// </summary>
		/// <param name="field">The field.</param>
		/// <returns>The field object.</returns>
		public static FieldDeclaration ToFieldDeclaration(this FieldDefinition field)
		{
            return new FieldDeclaration(
                            field.Name,
                            field.FieldType.ToTypeName(),
                            field.BuildObsoleteMarker(),
                            field.DeclaringType.ToTypeName())
                            {
                                IsProtected = field.IsProtectedField(),
                                IsConstant = field.IsLiteral
                            };
		}

        public static bool IsIncluded(this FieldDefinition field)
        {
            return field.IsPublicField() || field.IsProtectedField();
        }

		/// <summary>
		/// Extension method to determine if this field definition is public.
		/// </summary>
		/// <param name="field">The field.</param>
		/// <returns>True if it is public.</returns>
		public static bool IsPublicField(this FieldDefinition field)
		{
			if (field.IsSpecialName)
			{
				return false;
			}

			return field.IsPublic;
		}

        public static bool IsProtectedField(this FieldDefinition field)
        {
            if (field.IsSpecialName)
            {
                return false;
            }

            return field.IsFamily || field.IsFamilyAndAssembly || field.IsFamilyOrAssembly;
        }
	}
}
